package cn.mrlong.base.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentActivity
import cn.mrlong.base.ktnet.RetrofitManager
import cn.mrlong.base.ktnet.down.DowloadBuild
import cn.mrlong.base.ktnet.down.DownServer
import cn.mrlong.base.permission.PermissionUtils
import com.afollestad.materialdialogs.MaterialDialog
import com.kaopiz.kprogresshud.KProgressHUD
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import retrofit2.Response
import java.io.File

/**
 * 作者：BINGO
 * 时间：2021/04/22 09:23
 */
class AppUpdateApkUtil {
    public class AppVersionVo(var forceUpdate: String, var updateLog: String, var url: String)

    val savePath = "/Download"
    val saveName = "emdc.apk"
    private var progressBarHDKProgressHUD: KProgressHUD? = null

    /**
     * 提示升级
     * @param appVersionVo AppVersionVo
     */
    fun notice(appVersionVo: AppVersionVo, context: FragmentActivity) {
        PermissionUtils.requestPermissions(context,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            callback = { b: Boolean, _: List<String> ->
                if (b) {
                    MaterialDialog(context)
                        .show {
                            cancelable(false)
                            cancelOnTouchOutside(false)
                            title(text = "更新提示")
                            message(text = "${appVersionVo.updateLog}")
                            positiveButton(text = "升级", click = {
                                downApk(appVersionVo, context)
                            })
                            if ("1" == appVersionVo.forceUpdate) {
                                negativeButton(text = "取消")
                            }
                        }
                } else {
                    ToastUtil.show(context, "请开启内存卡读写权限！")
                }
            })
    }

    private fun downApk(appVersionVo: AppVersionVo, context: Context) {
        GlobalScope.launch(Dispatchers.Main) {
            if (null == progressBarHDKProgressHUD) {
                progressBarHDKProgressHUD =
                    KProgressHUD(context)
                        .setStyle(KProgressHUD.Style.BAR_DETERMINATE)
                        .setMaxProgress(100)
                        .setLabel("下载中...")
                        .setCancellable(false)
            }
            progressBarHDKProgressHUD?.setProgress(1)
            progressBarHDKProgressHUD?.show()

            withContext(Dispatchers.IO) {
                val response = RetrofitManager.get().create(DownServer::class.java)
                    .downloadFile(appVersionVo.url)
                dowload(context, response) {
                    setFileName = { saveName }
                    success {
                        //println(it.)
                        GlobalScope.launch(Dispatchers.Main) {
                            progressBarHDKProgressHUD?.dismiss()
                            openFile(it, context)
                        }
                    }
                    error {
                        GlobalScope.launch(Dispatchers.Main) {
                            it.printStackTrace()
                            progressBarHDKProgressHUD?.dismiss()
                        }
                    }
                    process { _, _, process ->
                        GlobalScope.launch(Dispatchers.Main) {
                            progressBarHDKProgressHUD?.setProgress((process * 100).toInt())
                            progressBarHDKProgressHUD?.setLabel("已下载${(process * 100).toInt()}%")
                        }
                    }
                }.startDowload()
            }
        }
    }

    private fun openFile(path: String, var1: Context) {
        try {
            val var2 = Intent()
            var2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            var2.action = Intent.ACTION_VIEW
            val filePath = File(path)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val authority = var1.packageName + ".fileprovider"
                val uriForFile = FileProvider.getUriForFile(var1, authority, filePath)
                var2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                var2.setDataAndType(uriForFile, var1.contentResolver.getType(uriForFile))
            } else {
                var2.setDataAndType(Uri.fromFile(filePath), getMIMEType(filePath))
            }
            var1.startActivity(var2)
        } catch (var5: Exception) {
            var5.printStackTrace()
            ToastUtil.show(var1, "没有找到打开此类文件的程序")
            //Toast.makeText(var1, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }
    }

    private fun getMIMEType(var0: File): String? {
        var var1: String? = ""
        val var2 = var0.name
        val var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length).toLowerCase()
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3)
        return var1
    }
}

suspend fun dowload(
    context: Context,
    response: Response<ResponseBody>,
    block: DowloadBuild.() -> Unit
): DowloadBuild {
    val build = DowloadBuild(context, response)
    build.block()
    return build
}